//
//  EJSAppDelegate.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/4/18.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSAppDelegate.h"
#import "EJSUserModel.h"
#import <IQKeyboardManager.h>
#import <Bugly/Bugly.h>
#import "SCSecureHelper.h"
#import "SCGestureSetController.h"
#import "WXApi.h"
#import "FlyLocalNotification.h"
#import "FlyMainTabBarViewController.h"
#import <UserNotifications/UserNotifications.h>
#import <BraintreeCore.h>
#import "WXApi.h"
#if (YiPinShangCheng == 1)//一品商城
#import <Stripe.h>
#import "CustomerServiceViewController.h"
#endif

#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>


@interface EJSAppDelegate()<UNUserNotificationCenterDelegate,JPUSHRegisterDelegate>

@property (assign, nonatomic)BOOL pushToMsgVC;

@end

@implementation EJSAppDelegate

+ (EJSAppDelegate *)sharedAppDelegate
{
    return (EJSAppDelegate *)[UIApplication sharedApplication].delegate;
}

- (UIWindow *)window
{
    if(!_window)
    {
        _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _window.backgroundColor = [UIColor whiteColor];
        [_window makeKeyAndVisible];
    }
    return _window;
}


- (void)entrTabBarViewController
{
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FlyMainTabBarViewController *tabBarViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"MainTabBarVC"];
    self.window.rootViewController = tabBarViewController;
    [EJSUserModel syncUserInfo];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (@available(iOS 11.0, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    //点击空白收回按钮
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"收起";

    [Bugly startWithAppId:@"1de145cb73"];
    [BTAppSwitch setReturnURLScheme:BTPaymentOpenUrl];
    [self entrTabBarViewController];
    [WXApi registerApp:WxAppKey universalLink:@""];
    [self registePush:launchOptions];

//#if (YiPinShangCheng == 1)//一品商城
//     [[IQKeyboardManager sharedManager].disabledDistanceHandlingClasses addObject:[CustomerServiceViewController class]];
//    [[STPPaymentConfiguration sharedConfiguration] setPublishableKey:@"pk_live_ajJt04KAE8BqhHRS18etZwqL"];
//#endif
    
    return YES;
}

/**
 * 推送处理1
 */
//注册用户通知设置
- (void)registePush:(NSDictionary *)launchOptions
{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
       
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey channel:@"App Store" apsForProduction:YES];
}

/**
 * 推送处理2
 */
//注册用户通知设置
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    // register to receive notifications
    [application registerForRemoteNotifications];
}

/**
 * 推送处理3
 */
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    
}


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNNotificationPresentationOptionBadge |
                      UNNotificationPresentationOptionAlert |
                      UNNotificationPresentationOptionSound);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)())completionHandler
{
    NSDictionary * userInfo = response.notification.request.content.userInfo;

    completionHandler(UIBackgroundFetchResultNewData);
}
#endif




- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if TARGET_IPHONE_SIMULATOR
    // 模拟器不能使用远程推送
#else
    // 请检查App的APNs的权限设置，更多内容可以参考文档
    // http://www.rongcloud.cn/docs/ios_push.html。
    NSLog(@"获取DeviceToken失败！！！");
    NSLog(@"ERROR：%@", error);
#endif
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // 为消息分享保存会话信息
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options
{
    if ([url.scheme localizedCaseInsensitiveCompare:BTPaymentOpenUrl] == NSOrderedSame) {
        return [BTAppSwitch handleOpenURL:url options:options];
    }
    if([WXApi handleOpenURL:url delegate:self])
    {
        return YES;
    }
    if([url.absoluteString hasPrefix:AppOpenUrl]){
        NSString *shareToken = [url.absoluteString substringFromIndex:AppOpenUrl.length + 3];
        [[NSUserDefaults standardUserDefaults] setObject:shareToken forKey:AppShareFromToken];
        return YES;
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if ([url.scheme localizedCaseInsensitiveCompare:BTPaymentOpenUrl] == NSOrderedSame) {
        return [BTAppSwitch handleOpenURL:url options:[NSDictionary dictionary]];
    }
    if([WXApi handleOpenURL:url delegate:self])
    {
        return YES;
    }
    if([url.absoluteString hasPrefix:AppOpenUrl]){
        NSString *shareToken = [url.absoluteString substringFromIndex:AppOpenUrl.length + 3];
        [[NSUserDefaults standardUserDefaults] setObject:shareToken forKey:AppShareFromToken];
        return YES;
    }
    return YES;
}


#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}


@end
